// pages/me/myWallet/myWallet.js
import { formatTimeDate } from '../../../utils/formatData';
import util from '../../../utils/utils'
import {
  CouponHttp
} from '../../../api/coupon.js'
const couponHttp = new CouponHttp();
const app = getApp()
Page({
  /**
   * 页面的初始数据
   */
  data: {
    isShowUseRule: -1,
    isShowUsePopup: false,
    couponInfo: [],
    page: 1
  },
  initPage() {
    this.httpGetCoupon();
  },
  //获取优惠券信息
  httpGetCoupon() {
    const {
      page,
      couponInfo
    } = this.data
    wx.stopPullDownRefresh();
    return couponHttp.getOperateCoupon({
      "page": this.data.page,
      "page_size": 10
    }).then((res) => {
      let data = this.formatData(res.coupons);
      console.log(res)
      this.setData({
        couponInfo: page === 1 ? data : couponInfo.concat(data),
      });
    })
  },

  formatData(res) {
    let i = 0;
    for(i;i<res.length;i++){
      res[i]['start_time'] = formatTimeDate(new Date(res[i]['start_time'].replace(/\.|\-/g, '/')),'yyyy/MM/dd');
      res[i]['end_time'] = formatTimeDate(new Date(res[i]['end_time'].replace(/\.|\-/g, '/')), 'yyyy/MM/dd');
      res[i]['created_time'] = formatTimeDate(new Date(res[i]['created_time'].replace(/\.|\-/g, '/')), 'yyyy-MM-dd')

    }
    console.log(res)
    return res
  },

  onUseCoupon(e) {
    console.log(1)
  },
  //下拉刷新
  onPullDownRefresh: function() {
    this.setData({
      page: 1
    })
    this.httpGetCoupon();
  },
  //上拉加载
  onReachBottom: function() {
    this.setData({
      page: this.data.page + 1
    });
    this.httpGetCoupon()
  },
  //自定义分享
  onShareAppMessage: function(res) {
    let userInfo = app.globalData.userInfo;
    let item;
    if (res.from === 'button') {
      item = res.target.dataset.item;
      console.log(item);
      let title    = userInfo.nickname + '给你发了一个红包';
      let path     = '/pages/redpackets/redpackets?nickname='+userInfo.nickname+'&ekey=' + item.ekey;
      let imageUrl = util.pageUrl + 'mini/images/share.png';
      if(item.hasOwnProperty('share_image') && item.share_image && item.share_image.indexOf('http') > -1){
        imageUrl = item.share_image;
      }
      if(item.hasOwnProperty('share_title') && item.share_title){
        title = item.share_title;
      }
      title = title.replace('{nickname}',userInfo.nickname);
      return {
        title: title,
        path: path,
        imageUrl: imageUrl
      }
    }
  },

  // 点击使用规则
  onShowUseRule(e) {
    if (e.target.dataset.index === this.data.isShowUseRule) {
      this.setData({
        isShowUseRule: -1
      });
      return
    }
    this.setData({
      isShowUseRule: e.target.dataset.index
    })
  }
});
